import argparse
import time
from loguru import logger
from configs import Configs
from strategies import Strategies
from orders import OrdersHelper
import commons


@logger.catch
def work():
    configs = Configs().get_configs_from_db()
    strategies = Strategies()

    while True:
        info = commons.get_client().get_account()
        balances = {i['asset']: i['free'] for i in info['balances']}

        logger.info(f"账户余额， BTC:{balances['BTC']}, {configs['交易对'][3:]}:{balances[configs['交易对'][3:]]}")

        # 更新配置
        configs = Configs().get_configs_from_db()
        logger.info(configs)

        if int(configs['程序on_off']) == 0:
            logger.debug("程序on_off为0，如需启动程序请配置程序on_off为1")
            time.sleep(30)
            continue

        if configs["程序k线"] not in configs["k线列表"]:
            logger.error("程序k线配置了k线列表以外的k线，退出")
            time.sleep(10)
            continue

        OrdersHelper().update_orders_db()

        # 拉取策略并执行
        strategies.process()

        # 睡眠防止接口调用过快
        time.sleep(float(Configs().get_configs()["每圈结束睡眠时间"]))


if __name__ == '__main__':
    # 验证环境配置
    from env_config import EnvConfig
    EnvConfig.validate_config()
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--clone_name", default=EnvConfig.get_clone_name())
    parser.add_argument("--api_key", default=EnvConfig.get_api_key())
    parser.add_argument("--secret_key", default=EnvConfig.get_api_secret())
    parser.add_argument("--test", default=EnvConfig.get_is_testnet(), action='store_true')
    args = parser.parse_args()
    clone_name = args.clone_name
    commons.MYSQL_DB = f"by3_{clone_name}"
    commons.API_KEY = args.api_key
    commons.API_SECRET = args.secret_key
    commons.IS_TESTNET = args.test

    logger.add(f"/log/log_{clone_name}.txt", rotation=EnvConfig.get_log_rotation_size())
    work()
